import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column } from '../stores/definitions_transfer';
import ABRouteTable from './ABRouteTable';

export default observer(({ showOrders, onAction }) => {
  const { ccPriceTransferStore: store } = useStore();
  const [counts, setCounts] = useState([]);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.data]);

  async function fetchOrderCounts() {
    const promiseAry = store.data.map((p) => store.api.orderCount({
      search: {
        startMainArea: p.startMainArea,
        startMinorAreas: p.startMinorAreas,
        endMainArea: p.endMainArea,
        endMinorAreas: p.endMinorAreas,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  const handleOpenEdit = (price) => {

  };

  const handleDelete = (price) => {
  };

  return (
    <TauTable
      primaryKey="id"
      tableLayout="fixed"
      currentPage={store.pg.page}
      pageSize={store.pg.size}
      total={store.total}
      sort={store.tableSort}
      onFetch={(pg) => { store.pg = pg; }}
      loading={store.loading}
      dataSource={toJS(store.data)}
      expandedRowRender={(row) => <ABRouteTable priceTransfer={row} />}
      expandedRowIndent={[300, 100]}
      // expandAll
      columns={[
        { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
        column('beginAreaName', {}),
        column('endAreaName', {}),
        column('priceConfig.specificSingleFare.RMB', { width: 180 }),
        column('dockingStationText', {}),
        { dataIndex: 'orderCount', title: t`订单`, width: 80, cell: (_, __, price) => <Button onClick={() => onAction?.(price, 'viewOrder')} type="primary" text>{counts.find((c) => c.id === price.id)?.count || 0}</Button> },
        column('state', { width: 88 }),
        {
          title: t`操作`,
          dataIndex: 'id',
          width: 100,
          cell: (_, __, price) => (
            <>
              <Button text type="primary" onClick={() => onAction?.(price, 'edit')} >{t`编辑`}</Button>
              <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
              <Button text type="primary" style={{ color: 'red' }} onClick={() => onAction?.(price, 'delete')} >{t`删除`}</Button>
            </>),
        },

      ].filter((c) => c.dataIndex !== 'orderCount' || showOrders)}
    />
  );
});
